package org.example.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.example.service.RpcRequest;
import org.example.service.JSONSerializer;
import org.example.service.RpcEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者
 */
public class RpcConsumer {
    //1.创建一个线程池对象 --处理自定义事件
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //2.声明一个自定义事件树立起 UserClientHandler
    private static UserClientHandler userClientHandler;


    //4.编写一个方法使用JDK动态代理连接对象


    //serviceClass 接口类型,根据那个接口生成子类代理对象;  providerParam : "UserService#sayHello#"
    public Object createProxy(Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //1) 初始化客户端
                if (userClientHandler == null) {
                    initClient();
                }
                //封装
                RpcRequest request = new RpcRequest();
                String requestId = UUID.randomUUID().toString();
                System.out.println(requestId);
                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();

                Class<?>[] parameterTypes = method.getParameterTypes();

                request.setRequestId(requestId);
                request.setClassName(className);
                request.setMethodName(methodName);
                request.setParameterTypes(parameterTypes);
                request.setParameters(args);

                //设置参数
                userClientHandler.setParam(request);
                System.out.println(request);

                //去服务端请求数据
                return executor.submit(userClientHandler).get();

            }
        });
    }


    //3.编写方法,初始化客户端(创建线程池 bootstrap 设置bootstrap 连接服务器)
    public static void initClient() throws InterruptedException {
        //1) UserClientHandler
        userClientHandler = new UserClientHandler();
        //2) 创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3) 创建客户端引导对象
        Bootstrap bootstrap = new Bootstrap();
        //4) 设置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                //监听channel并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //获取 ChannelPipeline
                        ChannelPipeline pipeline = ch.pipeline();
                        //设置编码
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new StringDecoder());
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        //5) 连接服务端
        bootstrap.connect("127.0.0.1", 9999).sync();

    }


}






















